<?php

namespace app\common\logic;

use app\common\model\Cart;
use think\Exception;
use think\exception\ValidateException;
use think\helper\Str;

class CartLogic  extends BaseLogic
{
    public static function addToCart($data)
    {
        try {
            validate(\app\validate\Cart::class)->check($data);
            $cart = Cart::where("user_id",$data['user_id'])
                ->where('goods_item_id',$data['id'])->find();
            if ($cart) {
                $cart->num += $data['num'];
                $cart->save();
            } else {
                $data['goods_item_id'] = $data['id'];
                unset($data['id']);
                Cart::create($data);
            }
        } catch (ValidateException | Exception $exception) {
            throwError($exception->getMessage());
        }
    }

    public static function delToCart($data)
    {
        Cart::where("user_id",$data['user_id'])->where('id',$data['id'])->delete();
    }

    public static function clearCart($data)
    {
        Cart::where("user_id",$data['user_id'])->delete();
    }
}